package cn.itcast.service.cargo.impl;

import cn.itcast.dao.cargo.FactoryDao;
import cn.itcast.dao.cargo.FactoryProductDao;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.domain.cargo.FactoryProduct;
import cn.itcast.domain.cargo.FactoryProductExample;
import cn.itcast.service.cargo.FactoryService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class FactoryServiceImpl implements FactoryService {

    @Autowired
    private FactoryDao factoryDao;

    @Autowired
    private FactoryProductDao factoryProductDao;

    //新增
    @Override
    public void save(Factory factory) {
        //设置id
        factory.setId(UUID.randomUUID().toString().replace("-",""));
        //设置时间
        factory.setCreateTime(new Date());
        factory.setUpdateTime(new Date());
        //保存
        factoryDao.insertSelective(factory);
    }

    @Override
    public void update(Factory factory) {
        factoryDao.updateByPrimaryKeySelective(factory);
    }

    @Override
    public void delete(String id) {
        //删除厂家下的产品
        //1.根据厂家id获取产品
        FactoryProductExample factoryProductExample = new FactoryProductExample();
        FactoryProductExample.Criteria criteria = factoryProductExample.createCriteria();
        criteria.andFactoryIdEqualTo(id);
        List<FactoryProduct> factoryProductList = factoryProductDao.selectByExample(factoryProductExample);
        //2.遍历查询出来的厂家下的产品，删除每一个产品
        for (FactoryProduct factoryProduct : factoryProductList) {
            factoryProductDao.deleteByPrimaryKey(factoryProduct.getId());
        }
        //删除厂家
        factoryDao.deleteByPrimaryKey(id);
    }

    @Override
    public Factory findById(String id) {
        return factoryDao.selectByPrimaryKey(id);
    }

    @Override
    public List<Factory> findAll(FactoryExample example) {
        return factoryDao.selectByExample(example);
    }

    @Override
    public PageInfo findByList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Factory> factoryList = factoryDao.findList();
        PageInfo pageInfo = new PageInfo(factoryList);
        return pageInfo;
    }

    //查ctype
    @Override
    public List<Factory> findCtype() {
        return factoryDao.findCtype();
    }
}
